package com.youlu.campus.service.recycle.convert;

import com.youlu.campus.entity.recycle.RecycleOrderInfo;
import com.youlu.campus.entity.recycle.dto.RecycleItemSaveDTO;
import com.youlu.campus.entity.recycle.RecycleItemInfo;
import com.youlu.campus.entity.recycle.vo.RecycleOrderInfoVo;
import com.youlu.campus.service.recycle.service.RecycleItemInfoService;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * @author : [dengbo]
 * @className : ActivetyCourse
 * @description : [回收商品转化]
 * @createTime : [2022/5/16 18:37]
 */
@Service
public class RecycleItemConvert {

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private RecycleItemInfoService recycleItemInfoService;

    public RecycleItemInfo recycleItemToEntity(RecycleItemSaveDTO dto, RecycleItemInfo info) {
        if (info == null) {
            info = new RecycleItemInfo();
            info.setCreatedTime(new Date());
            info.setDeleted(false);
        }
        info.setName(dto.getName());
        info.setImageUrl(dto.getImageUrl());
        info.setPrice(dto.getPrice());
        info.setDetail(dto.getDetail());
        info.setOnSale(dto.getOnSale());
        return info;
    }

    public List<RecycleOrderInfoVo> recycleOrderToVo(List<RecycleOrderInfo> orderInfos) {
        List<String> itemIds = orderInfos.stream().map(RecycleOrderInfo::getItemId).collect(Collectors.toList());
        List<RecycleItemInfo> itemInfos = recycleItemInfoService.getItemListByIdList(itemIds);
        Map<String, RecycleItemInfo> map = itemInfos.stream().collect(Collectors.toMap(RecycleItemInfo::getId, Function.identity(), (o1, o2) -> o2));
        return orderInfos.stream().map(item -> {
            RecycleOrderInfoVo vo = mapperFacade.map(item, RecycleOrderInfoVo.class);
            RecycleItemInfo itemInfo = map.get(item.getItemId());
            if (itemInfo != null) {
                vo.setItemName(itemInfo.getName());
                vo.setItemImageUrl(itemInfo.getImageUrl());
            }
            return vo;
        }).collect(Collectors.toList());
    }
}
